/
JavaScript.cs
550 lines (489 loc) · 23.6 KB
/
JavaScript.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information
namespace DotNetNuke.Framework.JavaScriptLibraries
{
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Web;
using System.Web.UI;
using DotNetNuke.Common;
using DotNetNuke.Common.Utilities;
using DotNetNuke.Entities.Controllers;
using DotNetNuke.Entities.Host;
using DotNetNuke.Entities.Portals;
using DotNetNuke.Entities.Users;
using DotNetNuke.Services.Installer.Packages;
using DotNetNuke.Services.Localization;
using DotNetNuke.Services.Log.EventLog;
using DotNetNuke.UI.Skins;
using DotNetNuke.UI.Skins.Controls;
using DotNetNuke.UI.Utilities;
using DotNetNuke.Web.Client;
using DotNetNuke.Web.Client.ClientResourceManagement;
using Globals = DotNetNuke.Common.Globals;
public class JavaScript
{
private const string ScriptPrefix = "JSL.";
private const string LegacyPrefix = "LEGACY.";
private const string JQueryUIDebugFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.js";
private const string JQueryUIMinFile = "~/Resources/Shared/Scripts/jquery/jquery-ui.min.js";
/// <summary>Initializes a new instance of the <see cref="JavaScript"/> class.</summary>
protected JavaScript()
{
}
/// <summary>checks whether the script file is a known javascript library.</summary>
/// <param name="jsname">script identifier.</param>
/// <returns><see langword="true"/> if a library with the given name is installed, otherwise <see langword="false"/>.</returns>
public static bool IsInstalled(string jsname)
{
JavaScriptLibrary library = JavaScriptLibraryController.Instance.GetLibrary(l => l.LibraryName.Equals(jsname, StringComparison.OrdinalIgnoreCase));
return library != null;
}
/// <summary>determine whether to use the debug script for a file.</summary>
/// <returns>whether to use the debug script.</returns>
public static bool UseDebugScript()
{
if (Globals.Status != Globals.UpgradeStatus.None)
{
return false;
}
return HttpContextSource.Current.IsDebuggingEnabled;
}
/// <summary>Returns the version of a javascript library from the database.</summary>
/// <param name="jsname">the library name.</param>
/// <returns>The highest version number of the library or <see cref="string.Empty"/>.</returns>
public static string Version(string jsname)
{
JavaScriptLibrary library = GetHighestVersionLibrary(jsname);
return library != null ? Convert.ToString(library.Version) : string.Empty;
}
/// <summary>Requests a script to be added to the page.</summary>
/// <param name="jsname">the library name.</param>
public static void RequestRegistration(string jsname)
{
// handle case where script has no javascript library
switch (jsname)
{
case CommonJs.jQuery:
RequestRegistration(CommonJs.jQueryMigrate);
break;
}
RequestRegistration(jsname, null, SpecificVersion.Latest);
}
/// <summary>Requests a script to be added to the page.</summary>
/// <param name="jsname">the library name.</param>
/// <param name="version">the library's version.</param>
public static void RequestRegistration(string jsname, Version version)
{
RequestRegistration(jsname, version, SpecificVersion.Exact);
}
/// <summary>Requests a script to be added to the page.</summary>
/// <param name="jsname">the library name.</param>
/// <param name="version">the library's version.</param>
/// <param name="specific">
/// how much of the <paramref name="version"/> to pay attention to.
/// When <see cref="SpecificVersion.Latest"/> is passed, ignore the <paramref name="version"/>.
/// When <see cref="SpecificVersion.LatestMajor"/> is passed, match the major version.
/// When <see cref="SpecificVersion.LatestMinor"/> is passed, match the major and minor versions.
/// When <see cref="SpecificVersion.Exact"/> is passed, match all parts of the version.
/// </param>
public static void RequestRegistration(string jsname, Version version, SpecificVersion specific)
{
switch (specific)
{
case SpecificVersion.Latest:
RequestHighestVersionLibraryRegistration(jsname);
return;
case SpecificVersion.LatestMajor:
case SpecificVersion.LatestMinor:
if (RequestLooseVersionLibraryRegistration(jsname, version, specific))
{
return;
}
break;
case SpecificVersion.Exact:
RequestSpecificVersionLibraryRegistration(jsname, version);
return;
}
// this should only occur if packages are incorrect or a RequestRegistration call has a typo
LogCollision(string.Format("Missing specific version library - {0},{1},{2}", jsname, version, specific));
}
/// <summary>method is called once per page event cycle and will load all scripts requested during that page processing cycle.</summary>
/// <param name="page">reference to the current page.</param>
public static void Register(Page page)
{
HandlePreInstallorLegacyItemRequests(page);
IEnumerable<string> scripts = GetScriptVersions();
IEnumerable<JavaScriptLibrary> finalScripts = ResolveVersionConflicts(scripts);
foreach (JavaScriptLibrary jsl in finalScripts)
{
RegisterScript(page, jsl);
}
}
public static string JQueryUIFile(bool getMinFile)
{
string jfile = JQueryUIDebugFile;
if (getMinFile)
{
jfile = JQueryUIMinFile;
}
return jfile;
}
public static string GetJQueryScriptReference()
{
#pragma warning disable 618
string scriptsrc = jQuery.HostedUrl;
if (!jQuery.UseHostedScript)
{
scriptsrc = jQuery.JQueryFile(!jQuery.UseDebugScript);
}
return scriptsrc;
#pragma warning restore 618
}
public static void RegisterClientReference(Page page, ClientAPI.ClientNamespaceReferences reference)
{
switch (reference)
{
case ClientAPI.ClientNamespaceReferences.dnn:
case ClientAPI.ClientNamespaceReferences.dnn_dom:
if (HttpContextSource.Current.Items.Contains(LegacyPrefix + "dnn.js"))
{
break;
}
ClientResourceManager.RegisterScript(page, ClientAPI.ScriptPath + "dnn.js", 12);
HttpContextSource.Current.Items.Add(LegacyPrefix + "dnn.js", true);
page.ClientScript.RegisterClientScriptBlock(page.GetType(), "dnn.js", string.Empty);
if (!ClientAPI.BrowserSupportsFunctionality(ClientAPI.ClientFunctionality.SingleCharDelimiters))
{
ClientAPI.RegisterClientVariable(page, "__scdoff", "1", true);
}
if (!ClientAPI.UseExternalScripts)
{
ClientAPI.RegisterEmbeddedResource(page, "dnn.scripts.js", typeof(ClientAPI));
}
break;
case ClientAPI.ClientNamespaceReferences.dnn_dom_positioning:
RegisterClientReference(page, ClientAPI.ClientNamespaceReferences.dnn);
ClientResourceManager.RegisterScript(page, ClientAPI.ScriptPath + "dnn.dom.positioning.js", 13);
break;
}
}
private static void RequestHighestVersionLibraryRegistration(string jsname)
{
var library = GetHighestVersionLibrary(jsname);
if (library != null)
{
AddItemRequest(library.JavaScriptLibraryID);
}
else
{
// covers case where upgrading to 7.2.0 and JSL's are not installed
AddPreInstallorLegacyItemRequest(jsname);
}
}
private static bool RequestLooseVersionLibraryRegistration(string jsname, Version version, SpecificVersion specific)
{
Func<JavaScriptLibrary, bool> isValidLibrary = specific == SpecificVersion.LatestMajor
? (Func<JavaScriptLibrary, bool>)(l => l.Version.Major == version.Major && l.Version.Minor >= version.Minor)
: l => l.Version.Major == version.Major && l.Version.Minor == version.Minor && l.Version.Build >= version.Build;
var library = JavaScriptLibraryController.Instance.GetLibraries(l => l.LibraryName.Equals(jsname, StringComparison.OrdinalIgnoreCase))
.OrderByDescending(l => l.Version)
.FirstOrDefault(isValidLibrary);
if (library != null)
{
AddItemRequest(library.JavaScriptLibraryID);
return true;
}
// unable to find a higher major version
library = GetHighestVersionLibrary(jsname);
if (library != null)
{
AddItemRequest(library.JavaScriptLibraryID);
LogCollision("Requested:" + jsname + ":" + version + ":" + specific + ".Resolved:" + library.Version);
return true;
}
return false;
}
private static void RequestSpecificVersionLibraryRegistration(string jsname, Version version)
{
JavaScriptLibrary library = JavaScriptLibraryController.Instance.GetLibrary(l => l.LibraryName.Equals(jsname, StringComparison.OrdinalIgnoreCase) && l.Version == version);
if (library != null)
{
AddItemRequest(library.JavaScriptLibraryID);
}
else
{
// this will only occur if a specific library is requested and not available
LogCollision(string.Format("Missing Library request - {0} : {1}", jsname, version));
}
}
private static void AddItemRequest(int javaScriptLibraryId)
{
HttpContextSource.Current.Items[ScriptPrefix + javaScriptLibraryId] = true;
}
private static void AddPreInstallorLegacyItemRequest(string jsl)
{
HttpContextSource.Current.Items[LegacyPrefix + jsl] = true;
}
private static IEnumerable<JavaScriptLibrary> ResolveVersionConflicts(IEnumerable<string> scripts)
{
var finalScripts = new List<JavaScriptLibrary>();
foreach (string libraryId in scripts)
{
var processingLibrary = JavaScriptLibraryController.Instance.GetLibrary(l => l.JavaScriptLibraryID.ToString(CultureInfo.InvariantCulture) == libraryId);
var existingLatestLibrary = finalScripts.FindAll(lib => lib.LibraryName.Equals(processingLibrary.LibraryName, StringComparison.OrdinalIgnoreCase))
.OrderByDescending(l => l.Version)
.SingleOrDefault();
if (existingLatestLibrary != null)
{
// determine previous registration for same JSL
if (existingLatestLibrary.Version > processingLibrary.Version)
{
// skip new library & log
var collisionText = string.Format(
CultureInfo.CurrentCulture,
"{0}-{1} -> {2}-{3}",
existingLatestLibrary.LibraryName,
existingLatestLibrary.Version,
processingLibrary.LibraryName,
processingLibrary.Version);
LogCollision(collisionText);
}
else if (existingLatestLibrary.Version != processingLibrary.Version)
{
finalScripts.Remove(existingLatestLibrary);
finalScripts.Add(processingLibrary);
}
}
else
{
finalScripts.Add(processingLibrary);
}
}
return finalScripts;
}
private static JavaScriptLibrary GetHighestVersionLibrary(string jsname)
{
if (Globals.Status == Globals.UpgradeStatus.Install)
{
// if in install process, then do not use JSL but all use the legacy versions.
return null;
}
try
{
return JavaScriptLibraryController.Instance.GetLibraries(l => l.LibraryName.Equals(jsname, StringComparison.OrdinalIgnoreCase))
.OrderByDescending(l => l.Version)
.FirstOrDefault();
}
catch (Exception)
{
// no library found (install or upgrade)
return null;
}
}
private static string GetScriptPath(JavaScriptLibrary js, Page page)
{
if (Host.CdnEnabled)
{
// load custom CDN path setting
var customCdn = HostController.Instance.GetString("CustomCDN_" + js.LibraryName);
if (!string.IsNullOrEmpty(customCdn))
{
return customCdn;
}
// cdn enabled but jsl does not have one defined
if (!string.IsNullOrEmpty(js.CDNPath))
{
var cdnPath = js.CDNPath;
if (cdnPath.StartsWith("//"))
{
cdnPath = $"{(UrlUtils.IsSecureConnectionOrSslOffload(page.Request) ? "https" : "http")}:{cdnPath}";
}
return cdnPath;
}
}
return "~/Resources/libraries/" + js.LibraryName + "/" + Globals.FormatVersion(js.Version, "00", 3, "_") + "/" + js.FileName;
}
private static string GetScriptLocation(JavaScriptLibrary js)
{
switch (js.PreferredScriptLocation)
{
case ScriptLocation.PageHead:
return "DnnPageHeaderProvider";
case ScriptLocation.BodyBottom:
return "DnnFormBottomProvider";
case ScriptLocation.BodyTop:
return "DnnBodyProvider";
}
return string.Empty;
}
private static IEnumerable<string> GetScriptVersions()
{
List<string> orderedScripts = (from object item in HttpContextSource.Current.Items.Keys
where item.ToString().StartsWith(ScriptPrefix)
select item.ToString().Substring(4)).ToList();
orderedScripts.Sort();
List<string> finalScripts = orderedScripts.ToList();
foreach (string libraryId in orderedScripts)
{
// find dependencies
var library = JavaScriptLibraryController.Instance.GetLibrary(l => l.JavaScriptLibraryID.ToString() == libraryId);
if (library == null)
{
continue;
}
foreach (var dependencyLibrary in GetAllDependencies(library).Distinct())
{
if (HttpContextSource.Current.Items[ScriptPrefix + "." + dependencyLibrary.JavaScriptLibraryID] == null)
{
finalScripts.Add(dependencyLibrary.JavaScriptLibraryID.ToString());
}
}
}
return finalScripts;
}
private static IEnumerable<JavaScriptLibrary> GetAllDependencies(JavaScriptLibrary library)
{
var package = PackageController.Instance.GetExtensionPackage(Null.NullInteger, p => p.PackageID == library.PackageID);
foreach (var dependency in package.Dependencies)
{
var dependencyLibrary = GetHighestVersionLibrary(dependency.PackageName);
yield return dependencyLibrary;
foreach (var childDependency in GetAllDependencies(dependencyLibrary))
{
yield return childDependency;
}
}
}
private static void LogCollision(string collisionText)
{
// need to log an event
EventLogController.Instance.AddLog(
"Javascript Libraries",
collisionText,
PortalController.Instance.GetCurrentPortalSettings(),
UserController.Instance.GetCurrentUserInfo().UserID,
EventLogController.EventLogType.SCRIPT_COLLISION);
string strMessage = Localization.GetString("ScriptCollision", Localization.SharedResourceFile);
var page = HttpContextSource.Current.Handler as Page;
if (page != null)
{
Skin.AddPageMessage(page, string.Empty, strMessage, ModuleMessage.ModuleMessageType.YellowWarning);
}
}
private static void RegisterScript(Page page, JavaScriptLibrary jsl)
{
if (string.IsNullOrEmpty(jsl.FileName))
{
return;
}
ClientResourceManager.RegisterScript(page, GetScriptPath(jsl, page), GetFileOrder(jsl), GetScriptLocation(jsl), jsl.LibraryName, jsl.Version.ToString(3));
if (Host.CdnEnabled && !string.IsNullOrEmpty(jsl.ObjectName))
{
string pagePortion;
switch (jsl.PreferredScriptLocation)
{
case ScriptLocation.PageHead:
pagePortion = "ClientDependencyHeadJs";
break;
case ScriptLocation.BodyBottom:
pagePortion = "ClientResourcesFormBottom";
break;
case ScriptLocation.BodyTop:
pagePortion = "BodySCRIPTS";
break;
default:
pagePortion = "BodySCRIPTS";
break;
}
Control scriptloader = page.FindControl(pagePortion);
var fallback = new DnnJsIncludeFallback(jsl.ObjectName, VirtualPathUtility.ToAbsolute("~/Resources/libraries/" + jsl.LibraryName + "/" + Globals.FormatVersion(jsl.Version, "00", 3, "_") + "/" + jsl.FileName));
if (scriptloader != null)
{
// add the fallback control after script loader.
var index = scriptloader.Parent.Controls.IndexOf(scriptloader);
scriptloader.Parent.Controls.AddAt(index + 1, fallback);
}
}
}
private static int GetFileOrder(JavaScriptLibrary jsl)
{
switch (jsl.LibraryName)
{
case CommonJs.jQuery:
return (int)FileOrder.Js.jQuery;
case CommonJs.jQueryMigrate:
return (int)FileOrder.Js.jQueryMigrate;
case CommonJs.jQueryUI:
return (int)FileOrder.Js.jQueryUI;
case CommonJs.HoverIntent:
return (int)FileOrder.Js.HoverIntent;
default:
return jsl.PackageID + (int)FileOrder.Js.DefaultPriority;
}
}
private static void HandlePreInstallorLegacyItemRequests(Page page)
{
List<string> legacyScripts = (from object item in HttpContextSource.Current.Items.Keys
where item.ToString().StartsWith(LegacyPrefix)
select item.ToString().Substring(7)).ToList();
#pragma warning disable 618
foreach (string legacyScript in legacyScripts)
{
switch (legacyScript)
{
case CommonJs.jQuery:
if (GetHighestVersionLibrary(CommonJs.jQuery) == null)
{
ClientResourceManager.RegisterScript(
page,
jQuery.GetJQueryScriptReference(),
FileOrder.Js.jQuery,
"DnnPageHeaderProvider");
}
if (GetHighestVersionLibrary(CommonJs.jQueryMigrate) == null)
{
ClientResourceManager.RegisterScript(
page,
jQuery.GetJQueryMigrateScriptReference(),
FileOrder.Js.jQueryMigrate,
"DnnPageHeaderProvider");
}
break;
case CommonJs.jQueryUI:
// register dependency
if (GetHighestVersionLibrary(CommonJs.jQuery) == null)
{
ClientResourceManager.RegisterScript(
page,
jQuery.GetJQueryScriptReference(),
FileOrder.Js.jQuery,
"DnnPageHeaderProvider");
}
if (GetHighestVersionLibrary(CommonJs.jQueryMigrate) == null)
{
ClientResourceManager.RegisterScript(
page,
jQuery.GetJQueryMigrateScriptReference(),
FileOrder.Js.jQueryMigrate,
"DnnPageHeaderProvider");
}
// actual jqueryui
if (GetHighestVersionLibrary(CommonJs.jQueryUI) == null)
{
ClientResourceManager.RegisterScript(
page,
jQuery.GetJQueryUIScriptReference(),
FileOrder.Js.jQueryUI,
"DnnPageHeaderProvider");
}
break;
}
}
#pragma warning restore 618
}
}
}